<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useWorkspaceStore } from '../stores/workspace';

const { t } = useI18n();
const workspaceStore = useWorkspaceStore();

// 本地状态
const showSettings = ref(false);
const maxDepthLocal = ref(8);
const excludePatternsText = ref('');
const autoIndexingEnabled = ref(true);

// 响应式数据
const indexer = workspaceStore.indexer;
const isIndexing = indexer.isIndexing;
const progress = indexer.progress;
const progressPercent = indexer.progressPercent;
const estimatedTime = indexer.estimatedTimeRemaining;

// 计算属性
const hasWorkspace = computed(() => !!workspaceStore.workspaceRoot);

const statusText = computed(() => {
  const p = progress.value;
  
  switch (p.phase) {
    case 'idle':
      return t('indexing.status.idle', '索引空闲');
    case 'scanning':
      return t('indexing.status.scanning', '正在扫描...');
    case 'building':
      return t('indexing.status.building', '正在构建...');
    case 'complete':
      return t('indexing.status.complete', '构建完成');
    case 'error':
      return t('indexing.status.error', '构建失败');
    default:
      return '';
  }
});

const progressInfo = computed(() => {
  const p = progress.value;
  if (p.totalCount === 0) return '';
  
  const percent = progressPercent.value?.value || 0;
  const remaining = estimatedTime.value?.value;
  
  let info = `${p.processedCount}/${p.totalCount} (${percent}%)`;
  
  if (remaining && remaining > 0) {
    if (remaining < 60) {
      info += ` • ${t('common.remaining', '剩余')} ${remaining}s`;
    } else {
      const minutes = Math.floor(remaining / 60);
      const seconds = remaining % 60;
      info += ` • ${t('common.remaining', '剩余')} ${minutes}m ${seconds}s`;
    }
  }
  
  return info;
});

const defaultExcludePatterns = [
  'node_modules',
  '.git',
  '.svn', 
  '.hg',
  'target',
  'build',
  'dist',
  'out',
  '*.log',
  '.DS_Store',
  'Thumbs.db'
];

// 方法
async function startIndexing() {
  if (!hasWorkspace.value) return;
  
  const excludePatterns = excludePatternsText.value
    .split('\n')
    .map(p => p.trim())
    .filter(p => p.length > 0);
    
  const options = {
    maxDepth: maxDepthLocal.value,
    excludePatterns: excludePatterns.length > 0 ? excludePatterns : defaultExcludePatterns
  };
  
  await workspaceStore.startWorkspaceIndexing(options);
}

function stopIndexing() {
  workspaceStore.stopWorkspaceIndexing();
}

function clearIndex() {
  workspaceStore.clearWorkspaceIndex();
}

function resetSettings() {
  maxDepthLocal.value = 8;
  excludePatternsText.value = defaultExcludePatterns.join('\n');
  autoIndexingEnabled.value = true;
}

// 监听自动索引设置变化
watch(autoIndexingEnabled, (enabled) => {
  workspaceStore.autoStartIndexing = enabled;
});

// 初始化设置
onMounted(() => {
  excludePatternsText.value = defaultExcludePatterns.join('\n');
  autoIndexingEnabled.value = workspaceStore.autoStartIndexing;
});
</script>

<template>
  <div class="flex flex-col gap-4 p-4">
    <!-- 标题和状态 -->
    <div class="flex items-center justify-between">
      <h3 class="text-lg font-semibold text-app-fg">
        {{ t('indexing.title', '工作区索引') }}
      </h3>
      <div class="flex items-center gap-2">
        <div
          class="w-2 h-2 rounded-full"
          :class="{
            'bg-gray-400': progress.phase === 'idle',
            'bg-blue-500 animate-pulse': progress.phase === 'scanning' || progress.phase === 'building',
            'bg-green-500': progress.phase === 'complete',
            'bg-red-500': progress.phase === 'error'
          }"
        ></div>
        <span class="text-sm text-muted-fg">{{ statusText }}</span>
      </div>
    </div>

    <!-- 进度信息 -->
    <div v-if="isIndexing" class="space-y-2">
      <div class="w-full bg-panel-border rounded-full h-2">
        <div
          class="bg-accent h-2 rounded-full transition-all duration-300"
          :style="{ width: `${progressPercent?.value || 0}%` }"
        ></div>
      </div>
      <div class="flex justify-between text-xs text-muted-fg">
        <span>{{ progressInfo }}</span>
        <span v-if="progress.currentPath" class="truncate max-w-48" :title="progress.currentPath">
          {{ progress.currentPath }}
        </span>
      </div>
    </div>

    <!-- 错误信息 -->
    <div v-if="progress.phase === 'error' && progress.error" class="p-3 bg-red-100 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-sm text-red-800 dark:text-red-200">
      {{ progress.error }}
    </div>

    <!-- 控制按钮 -->
    <div class="flex items-center gap-2">
      <button
        v-if="!isIndexing"
        @click="startIndexing"
        :disabled="!hasWorkspace"
        class="px-3 py-2 bg-accent text-accent-fg rounded hover:bg-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
      >
        {{ t('indexing.start', '开始构建索引') }}
      </button>
      
      <button
        v-else
        @click="stopIndexing"
        class="px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700 text-sm"
      >
        {{ t('indexing.stop', '停止构建') }}
      </button>

      <button
        @click="clearIndex"
        :disabled="isIndexing"
        class="px-3 py-2 bg-panel-border text-app-fg rounded hover:bg-panel-border/80 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
      >
        {{ t('indexing.clear', '清空索引') }}
      </button>

      <button
        @click="showSettings = !showSettings"
        class="px-3 py-2 bg-panel-border text-app-fg rounded hover:bg-panel-border/80 text-sm"
      >
        {{ t('common.settings', '设置') }}
      </button>
    </div>

    <!-- 设置面板 -->
    <div v-if="showSettings" class="space-y-4 p-4 bg-panel-bg/50 rounded border border-panel-border">
      <h4 class="font-medium text-app-fg">{{ t('indexing.settings.title', '索引设置') }}</h4>
      
      <!-- 自动索引 -->
      <div class="flex items-center gap-2">
        <input
          id="auto-indexing"
          v-model="autoIndexingEnabled"
          type="checkbox"
          class="rounded border-panel-border"
        />
        <label for="auto-indexing" class="text-sm text-app-fg">
          {{ t('indexing.settings.auto', '自动构建索引') }}
        </label>
      </div>

      <!-- 最大深度 -->
      <div class="space-y-2">
        <label class="block text-sm font-medium text-app-fg">
          {{ t('indexing.settings.maxDepth', '最大扫描深度') }}
        </label>
        <input
          v-model.number="maxDepthLocal"
          type="number"
          min="1"
          max="20"
          class="w-full px-3 py-2 border border-panel-border rounded bg-panel-bg text-app-fg focus:outline-none focus:ring-2 focus:ring-accent"
        />
        <p class="text-xs text-muted-fg">
          {{ t('indexing.settings.maxDepthDesc', '限制目录扫描的最大深度，避免过深的嵌套') }}
        </p>
      </div>

      <!-- 排除模式 -->
      <div class="space-y-2">
        <label class="block text-sm font-medium text-app-fg">
          {{ t('indexing.settings.exclude', '排除模式') }}
        </label>
        <textarea
          v-model="excludePatternsText"
          rows="6"
          class="w-full px-3 py-2 border border-panel-border rounded bg-panel-bg text-app-fg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-accent resize-none"
          placeholder="node_modules&#10;.git&#10;*.log"
        ></textarea>
        <p class="text-xs text-muted-fg">
          {{ t('indexing.settings.excludeDesc', '每行一个模式，支持通配符如 *.log') }}
        </p>
      </div>

      <!-- 设置操作 -->
      <div class="flex items-center gap-2 pt-2">
        <button
          @click="resetSettings"
          class="px-3 py-1.5 text-sm bg-panel-border text-app-fg rounded hover:bg-panel-border/80"
        >
          {{ t('common.reset', '重置') }}
        </button>
        <button
          @click="showSettings = false"
          class="px-3 py-1.5 text-sm bg-accent text-accent-fg rounded hover:bg-accent/90"
        >
          {{ t('common.close', '关闭') }}
        </button>
      </div>
    </div>
  </div>
</template>